package com.fintech.pangu.service;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.escape.Escaper;
import com.google.common.net.UrlEscapers;
import com.google.gson.Gson;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.Map;

/**
 * @Description:
 */
public abstract class AbstractService {

    private static final Escaper pathEscaper = UrlEscapers.urlPathSegmentEscaper();
    private static final Escaper queryParamEscaper = UrlEscapers.urlFormParameterEscaper();

    private final String baseUrl;

    protected final Gson gson;

    protected final RestTemplate restTemplate;


    public AbstractService(String baseUrl, Gson gson,RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.baseUrl = baseUrl;
        this.gson = gson;
    }

    protected String escapePath(String path) {
        return pathEscaper.escape(path);
    }

    protected String escapeParam(String param) {
        return queryParamEscaper.escape(param);
    }

    protected void checkNotEmpty(String value, String name) {
        Preconditions.checkArgument(!Strings.isNullOrEmpty(value), name + " should not be null or empty");
    }

    protected String get(String path) {
        return restTemplate.getForObject(String.format("%s/%s", baseUrl, path),String.class);
    }

    protected String post(String path, Object request){
        return restTemplate.postForObject(String.format("%s/%s", baseUrl, path),request,String.class);
    }

    protected void put(String path, Object request, Map uriVariables){
         restTemplate.put(String.format("%s/%s", baseUrl, path),request,uriVariables);
    }

    protected void delete(String path){
         restTemplate.delete(URI.create(String.format("%s/%s", baseUrl, path)));
    }



}
